package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzMapper clazzMapper;
    /**
     * 分页查询
     */
    @Override
    public PageResult<Student> findPage(StudentQueryParam param) {
        Page<Student> studentPage = new Page<>(param.getPage(), param.getPageSize());

        studentPage.addOrder(OrderItem.desc("update_time"));

        //对姓名，学历，班级进行条件查询
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<Student>()
                .like(!StringUtils.isEmpty(param.getName()), Student::getName, param.getName())
                .eq(param.getDegree() != null, Student::getDegree, param.getDegree())
                .eq(param.getClazzId() != null, Student::getClazzId, param.getClazzId());
        this.page(studentPage, queryWrapper);

        List<Student> studentList = studentPage.getRecords();
        //根据班级id查询班级姓名
        studentList.forEach(student -> {
            Integer clazzId = student.getClazzId();
            Clazz clazz=clazzMapper.selectById(clazzId);
            if (clazz != null) {
                student.setClazzName(clazz.getName());
            }
        });

        return new PageResult<>(studentPage.getTotal(), studentPage.getRecords());
    }

    /**
     * 新增学生信息
     * @param student
     */
    @Override
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        save(student);
    }

    /**
     * 修改学生信息
     *
     * @param student
     */
    @Override
    public void updateStuById(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }

    /**
     * 违纪处理
     */
    @Override
    public void violation(Integer id, Integer score) {
        Student student = getById(id);
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));
        updateById(student);
    }
}
